<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <div>
        <el-alert
          :title="runTimestampTitle"
          type="success"
          :closable="false">
        </el-alert>
        <el-alert title="打卡点可以不选！！可能导致打卡点跟轨迹不在一条线上！" type="warning" show-icon> </el-alert>
        <div style="margin-top:10px">

          <el-form-item label="选择打卡点" prop="selectPointArray" >
            <el-select
              size="medium"
              v-model="form.selectPointArray"
              multiple
              :multiple-limit="2"
              placeholder="请选择">
              <el-option
                v-for="point in pointList"
                :key="point.id"
                :label="point.address"
                :value="point.id"
              >
              </el-option>
            </el-select>
          </el-form-item>

        </div>

        <el-divider content-position="left"></el-divider>
        <el-form-item label="选择轨迹" prop="recordId">
          <el-select size="medium" v-model="form.recordId" placeholder="请选择">
              <el-option v-for="item in recordList" :key="item.record" :label="item.title" :value="item.record">
              </el-option>
          </el-select>
        </el-form-item>

        <el-divider content-position="left">步频模拟</el-divider>
        <div class="settings" v-for="(item, index) in arr" :key="index">
          <el-slider
            v-model="arr[index]"
            vertical
            height="150px"
            :format-tooltip="formatTooltip"
          >
          </el-slider>
        </div>
      </div>
      <br />
      <el-tag>{{ realStepNum }}步</el-tag>

      <el-form-item label="公里数" prop="distance">
        <el-input placeholder="精确到2位小数：1.78" v-model="form.distance"></el-input>
      </el-form-item>

    </el-form>
    <el-button @click="stopRun">提交成绩</el-button>
    <el-button @click="runCancel">取消跑步</el-button>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》'
import { lepaoGetRecordList, lepaoStopRun, lepaoGetSchoolRuler, lepaoRunCancel, lepaoRunStatus } from "@/api/run";

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  props: { runTimestamp:'' },
  data() {
    //这里存放数据
    const validateDistance = (rule, value, callback) => {
      if (!/^[0-9]+(.[0-9]{2})?$/.test(value)) {
        callback(new Error("请输入正确的公里数"));
      } else {
        callback();
      }
    };

    const validateSelectPointArray = (rule, value, callback)=>{
      if(value.length === 2 || value.length === 0){
        callback();
      }else{
        callback(new Error("不选，或选择两个打卡点！"));
      }
    };

    const validateRecordId = (rule, value, callback)=>{
      if(value === ""){
        callback(new Error("请选择轨迹"));
      }else{
        callback();
      }
    };
    return {
      loading: false,
      //跑步次数
      totalNum: 0,
      pointList: [],
      recordList: [],
      arr: new Array(7).fill(0),
      stepInfo: [],
      form: {
        //用户选择的打卡点
        selectPointArray: [],
        distance: "",
        recordId: "",
      },
      rules: {
        distance: [{ required: true, trigger: "blur", validator: validateDistance }],
        selectPointArray: [{ required: true, trigger: "blur", validator:validateSelectPointArray }],
        recordId: [{ required: true, trigger: "blur", validator: validateRecordId }],
      },
    };
  },
  //计算属性 类似于data概念
  computed: {
    runTimestampTitle() {
      console.log(this.runTimestamp)
      var date = new Date(parseInt(this.runTimestamp) * 1000);
      var YY = date.getFullYear() + '-';
      var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
      var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
      var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
      var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
      var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
      return "开始跑步时间:" + YY + MM + DD +" "+hh + mm + ss;
    },
    realStepNum() {
      //清空数组
      this.stepInfo.splice(0, this.stepInfo.length);
      //生成步频
      this.arr.forEach((num) => {
        let relStep = Math.ceil(num * 15.5);
        this.stepInfo.push(Math.ceil(relStep * 0.32));
        this.stepInfo.push(Math.ceil(relStep * 0.38));
        this.stepInfo.push(Math.ceil(relStep * 0.27));
      });
      this.stepInfo.push(Math.ceil(this.stepInfo[this.stepInfo.length - 1] * 0.75));

      //算出总步数，前端显示
      let stepNum = 0;
      this.stepInfo.forEach((num) => {
        stepNum += num;
      });
      return stepNum;
    },
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    formatTooltip(val) {
      return Math.ceil(val * 15.5);
    },
    lepaoGetRecordList() {
      lepaoGetRecordList({ page: "1", year: "2021" })
        .then((data) => {
          // const { data } = response;
          this.recordList = data;
          if (data.code === 0) {
            
          }
        })
        .catch((err) => {this.$message.error(err.message)});
    },
    //跑步规则
    lepaoGetSchoolRuler() {
      lepaoGetSchoolRuler()
        .then((data) => {

          // const { data } = response;
          //可选跑步点
          const pointList = data.run_line_info.point_list;
          this.pointList = pointList;
          console.log(data);

          if (data.code === 0) {
            
          }
        })
        .catch((err) => {this.$message.error(err.message)});
    },
    // 提交成绩
    stopRun() {
      //先校验一下整个表单
      this.$refs["form"].validate((valid) => {
        if(valid){
          //找出两个打卡完整数据，放到数组中去。
          let result = [];
          this.pointList.forEach((point) => {
            if (this.form.selectPointArray[0] === point.id || this.form.selectPointArray[1] === point.id) {
              result.push(point);
            }
          });
          //校验是否步频每个都选了
          for (let index = 0; index < this.stepInfo.length; index++) {
            if(this.stepInfo[index] === 0){
              this.$tips("步频每个都要选哦！","error")
              return;
            }
          }

          this.loading = true;
          lepaoStopRun({
            stepInfo: this.stepInfo,
            recordId: this.form.recordId,
            distance: this.form.distance,
            pointList: result,
          })
            .then((response) => {
              this.loading = false;
              this.$tips(`${response.pass_tit}`,"success");
              this.$tips(`${response.record_failed_reason}`,"success");
              this.$tips(`${response.calDesc}`,"success");

              //提交后让父组件刷新，查看提交状态
              this.$emit('status');

              console.log(response);
            })
            .catch((err) => {
              this.loading = false;
              this.$message.error(err.message + "。重新提交试试！");
              });

        }else{
        }
      });
    },
    runCancel(){
      lepaoRunCancel().
      then((data) => {
        this.$tips(`取消成功`,"success");
        //取消后让父组件刷新，查看取消状态
        this.$emit('status');

        if(data.code === 0){
        }
      }).catch((err) => {
        this.$tips(`取消异常`,err.message);
      });
    },
  },
  //声明周期 - 创建完成（可以访问当前this实例）
  created() {
    //获取跑步记录
    this.lepaoGetRecordList();

    //获取跑步打卡点
    this.lepaoGetSchoolRuler();
  },
  //声明周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.settings {
  display: inline-block;
}
</style>